package main

import (
	"errors"
	"fmt"
	"time"

	"gitee.com/chen_wei_jing/kinx/zconf"
	"gitee.com/chen_wei_jing/kinx/zlog"

	"gitee.com/chen_wei_jing/kinx/ziface"
	"gitee.com/chen_wei_jing/kinx/znet"
)

type TestRouter struct {
	znet.BaseRouter
}

var dealTimes = 0

// PreHandle -
func (t *TestRouter) PreHandle(req ziface.IRequest) {
	start := time.Now()

	fmt.Println("--> Call PreHandle")
	if err := req.GetConnection().SendMsg(0, []byte("test1")); err != nil {
		fmt.Println(err)
	}
	elapsed := time.Since(start)
	fmt.Println("cost time：", elapsed)
}

// Handle -
func (t *TestRouter) Handle(req ziface.IRequest) {
	// fmt.Println("--> Call Handle")

	// if err := Err(); err != nil {
	// 	req.Abort()
	// 	fmt.Println("Insufficient permission")
	// }

	// dealTimes++
	// req.GetConnection().AddCloseCallback(nil, nil, func() {
	// 	fmt.Println("run close callback")
	// })

	// if err := req.GetConnection().SendMsg(0, []byte("test2")); err != nil {
	// 	fmt.Println(err)
	// }

	// if dealTimes == 5 {
	// 	req.GetConnection().Stop()
	// }

	// fmt.Printf("Handler recv: msgId=%d %s", req.GetMsgID(), string(req.GetData()))
	zlog.Infof("Handler recv: msgId=%d %s", req.GetMsgID(), string(req.GetData()))

	// time.Sleep(1 * time.Millisecond)
}

// PostHandle -
func (t *TestRouter) PostHandle(req ziface.IRequest) {
	fmt.Println("--> Call PostHandle")
	if err := req.GetConnection().SendMsg(0, []byte("test3")); err != nil {
		fmt.Println(err)
	}
}

func Err() error {
	//Specific Business Operation (具体业务操作)
	return errors.New("Test")
}

// heartbeat
// User-defined heartbeat message processing method
// 用户自定义的心跳检测消息处理方法
func myHeartBeatMsg(conn ziface.IConnection) []byte {
	return []byte("heartbeat, I am server, I am alive")
}

// User-defined handling method for remote connection not alive.
// 用户自定义的远程连接不存活时的处理方法
func myOnRemoteNotAlive(conn ziface.IConnection) {
	fmt.Println("myOnRemoteNotAlive is Called, connID=", conn.GetConnID(), "remoteAddr = ", conn.RemoteAddr())
	//关闭连接
	conn.Stop()
}

// User-defined method for handling heartbeat messages (用户自定义的心跳检测消息处理方法)
type myHeartBeatRouter struct {
	znet.BaseRouter
}

func (r *myHeartBeatRouter) Handle(request ziface.IRequest) {
	fmt.Println("in MyHeartBeatRouter Handle, recv from client : msgId=", request.GetMsgID(), ", data=", string(request.GetData()))
}

func main() {
	zlog.SetCons(zconf.GlobalObject.LogCons)
	// zlog.ResetFlags(zlog.BitDate | zlog.BitLongFile | zlog.BitLevel)
	s := znet.NewUserConfServer(&zconf.Config{
		Mode:               "kcp",
		KcpPort:            7777,
		KcpRecvWindow:      128,
		KcpSendWindow:      128,
		KcpStreamMode:      true,
		KcpACKNoDelay:      false,
		KcpFecDataShards:   10, //代表每10个原始数据块 发3个校验数据块
		KcpFecParityShards: 3,
		HeartbeatMax:       10, // 10秒内没有收到数据包,表示断线
	})

	s.AddRouter(1, &TestRouter{})
	s.SetOnConnStart(func(conn ziface.IConnection) {
		fmt.Println("--> OnConnStart")
	})

	// s.SetOnConnStop(func(conn ziface.IConnection) {
	// 	fmt.Println("-------------- stop ~~~~~~~~~~~~~~~~~~~")
	// 	fmt.Println("--> OnConnStop")
	// })

	// myHeartBeatMsgID := 88888

	// Start heartbeating detection. (启动心跳检测)
	// s.StartHeartBeatWithOption(1*time.Second, &ziface.HeartBeatOption{
	// 	MakeMsg:          myHeartBeatMsg,
	// 	OnRemoteNotAlive: myOnRemoteNotAlive,
	// 	Router:           &myHeartBeatRouter{},
	// 	HeartBeatMsgID:   uint32(myHeartBeatMsgID),
	// })

	s.StartHeartBeat(20 * time.Second)

	s.Serve()
}
